// ComponentStateTestPanel.js

class ComponentStateTestPanel {
    static instance = null;

    static initialize() {
        if (ComponentStateTestPanel.instance) {
            console.warn('ComponentStateTestPanel already initialized');
            return ComponentStateTestPanel.instance;
        }

        // 给容器一个合理的等待时间
        const maxAttempts = 10;
        let attempts = 0;

        const tryInitialize = () => {
            return new Promise((resolve, reject) => {
                const attempt = () => {
                    attempts++;
                    const container = document.getElementById('component-test');

                    if (container) {
                        try {
                            ComponentStateTestPanel.instance = new ComponentStateTestPanel(container);
                            console.log('Component state test panel initialized');
                            resolve(ComponentStateTestPanel.instance);
                        } catch (error) {
                            reject(error);
                        }
                    } else if (attempts < maxAttempts) {
                        // 等待100ms后重试
                        setTimeout(attempt, 100);
                    } else {
                        reject(new Error('Component state test panel container not found after multiple attempts'));
                    }
                };

                attempt();
            });
        };

        return tryInitialize();
    }

    // 初始化折叠功能
    initCollapseFeature() {
        // 检查容器是否已经被包装
        let panelContainer = this.container.closest('.left-panel-container');

        if (!panelContainer) {
            return; // 如果没有找到容器，直接返回，因为现在在 HTML 中已经定义了结构
        }

        // 获取折叠按钮
        const collapseButton = panelContainer.querySelector('.panel-collapse-button');

        if (collapseButton) {
            // 绑定折叠事件
            collapseButton.addEventListener('click', () => {
                panelContainer.classList.toggle('collapsed');

                // 更新图标方向
                const icon = collapseButton.querySelector('[data-lucide="chevron-left"]');
                if (icon) {
                    icon.style.transform = panelContainer.classList.contains('collapsed')
                        ? 'rotate(180deg)'
                        : 'rotate(0deg)';
                }
            });
        }
    }

    static destroy() {
        if (ComponentStateTestPanel.instance) {
            ComponentStateTestPanel.instance.destroy();
            ComponentStateTestPanel.instance = null;
        }
    }

    constructor(container) {
        if (ComponentStateTestPanel.instance) {
            return ComponentStateTestPanel.instance;
        }

        this.container = container;
        this.stateManager = window.robotStateManager;
        this.isTestMode = false; // 添加测试模式状态

        /*
        // 初始化折叠功能
        this.initCollapseFeature();
        */

        // 状态测试组定义
        this.testGroups = {
            drive: {
                title: '驱动系统',
                icon: 'truck',
                subGroups: {
                    left: {
                        label: '左轮',
                        icon: 'arrow-left',
                        tests: [
                            { name: '旋转', icon: 'refresh-ccw', stateKey: 'motion.wheels.left.rotating', type: 'toggle' },
                            { name: '离地', icon: 'arrow-up', stateKey: 'motion.wheels.left.offGround', type: 'toggle' },
                            { name: '速度', icon: 'gauge', stateKey: 'motion.wheels.left.speed', type: 'slider', min: 0, max: 1000, step: 0.01 }
                        ]
                    },
                    right: {
                        label: '右轮',
                        icon: 'arrow-right',
                        tests: [
                            { name: '旋转', icon: 'refresh-cw', stateKey: 'motion.wheels.right.rotating', type: 'toggle' },
                            { name: '离地', icon: 'arrow-up', stateKey: 'motion.wheels.right.offGround', type: 'toggle' },
                            { name: '速度', icon: 'gauge', stateKey: 'motion.wheels.right.speed', type: 'slider', min: 0, max: 1000, step: 0.01 }
                        ]
                    }
                }
            },
            cleaning: {
                title: '清扫系统',
                icon: 'trash-2',
                subGroups: {
                    brush: {
                        label: '刷子',
                        icon: 'refresh-cw',
                        tests: [
                            { name: '边刷', icon: 'rotate-ccw', stateKey: 'cleaning.brush.side.enabled', type: 'toggle' },
                            { name: '边刷速度', icon: 'gauge', stateKey: 'cleaning.brush.side.speed', type: 'slider', min: 0, max: 1000, step: 0.01 },
                            { name: '主刷', icon: 'rotate-cw', stateKey: 'cleaning.brush.main.enabled', type: 'toggle' },
                            { name: '主刷速度', icon: 'gauge', stateKey: 'cleaning.brush.main.speed', type: 'slider', min: 0, max: 1000, step: 0.01 }
                        ]
                    },
                    vacuum: {
                        label: '吸尘',
                        icon: 'wind',
                        tests: [
                            { name: '风机', icon: 'fan', stateKey: 'cleaning.vacuum.enabled', type: 'toggle' },
                            { name: '吸力', icon: 'gauge', stateKey: 'cleaning.vacuum.fanSpeed', type: 'slider', min: 0, max: 1000, step: 0.1 }
                        ]
                    },
                    mop: {  // 新增拖布控制组
                        label: '拖布',
                        icon: 'droplets',
                        tests: [
                            { name: '抬升', icon: 'arrow-up', stateKey: 'cleaning.mop.lift', type: 'toggle' },
                            { name: '震动', icon: 'audio-waveform',stateKey: 'cleaning.mop.vibrate', type: 'toggle' },
                            { name: '出水', icon: 'droplets',stateKey: 'cleaning.mop.waterFlow', type: 'slider', min: 0, max: 1000, step: 1 }
                        ]
                    }
                }
            },
            sensors: {
                title: '传感系统',
                icon: 'radio',
                subGroups: {
                    cameras: {  // 新增摄像头组
                        label: '摄像',
                        icon: 'camera',
                        tests: [
                            { name: '主摄', icon: 'camera', stateKey: 'sensors.camera.main.enabled', type: 'toggle' },
                            { name: '补光', icon: 'sun', stateKey: 'sensors.camera.main.fillLight', type: 'toggle' },
                            { name: '帧率', icon: 'timer', stateKey: 'sensors.camera.main.fps', type: 'slider', min: 0, max: 100, step: 1 }
                        ]
                    },
                    lidar: {
                        label: '激光雷达',
                        icon: 'scan-line',
                        tests: [
                            { name: '前碰', icon: 'arrow-up', stateKey: 'sensors.lidar.switches.front', type: 'toggle' },
                            { name: '后碰', icon: 'arrow-down', stateKey: 'sensors.lidar.switches.back', type: 'toggle' },
                            { name: '左碰', icon: 'arrow-left', stateKey: 'sensors.lidar.switches.left', type: 'toggle' },
                            { name: '右碰', icon: 'arrow-right', stateKey: 'sensors.lidar.switches.right', type: 'toggle' },
                            { name: '开关', icon: 'refresh-cw', stateKey: 'sensors.lidar.rotating', type: 'toggle' },
                            { name: '旋转速度', icon: 'gauge', stateKey: 'sensors.lidar.speed', type: 'slider', min: 0, max: 1000, step: 0.01 }
                        ]
                    },
                    frontBumper: {  // 添加前碰撞组
                        label: '前碰',
                        icon: 'alert-circle',
                        tests: [
                            { name: '左前', icon: 'arrow-up-left', stateKey: 'sensors.frontBumper.left', type: 'toggle' },
                            { name: '右前', icon: 'arrow-up-right', stateKey: 'sensors.frontBumper.right', type: 'toggle' }
                        ]
                    },
                    cliff: {
                        label: '悬崖',
                        icon: 'scan-line', // 新增组图标
                        tests: [
                            { name: '左侧', icon: 'chevron-left', stateKey: 'sensors.cliff.left', type: 'toggle' },
                            { name: '左前', icon: 'corner-up-left', stateKey: 'sensors.cliff.frontLeft', type: 'toggle' },
                            { name: '右前', icon: 'corner-up-right', stateKey: 'sensors.cliff.frontRight', type: 'toggle' },
                            { name: '右侧', icon: 'chevron-right', stateKey: 'sensors.cliff.right', type: 'toggle' }
                        ]
                    },
                    ir: {
                        label: '红外',
                        icon: 'radio-tower',
                        tests: [
                            { name: '左--侧', icon: 'cast', stateKey: 'sensors.ir.left', type: 'toggle' },
                            { name: '左中侧', icon: 'cast', stateKey: 'sensors.ir.leftMid', type: 'toggle' },
                            { name: '左前侧', icon: 'cast', stateKey: 'sensors.ir.leftRear', type: 'toggle' },
                            { name: '右--侧', icon: 'cast', stateKey: 'sensors.ir.rightRear', type: 'toggle' },
                            { name: '右中侧', icon: 'cast', stateKey: 'sensors.ir.rightMid', type: 'toggle' },
                            { name: '右前侧', icon: 'cast', stateKey: 'sensors.ir.right', type: 'toggle' }
                        ]
                    },
                    other: {
                        label: '其他',
                        icon: 'rss',
                        tests: [
                            { name: '线激光', icon: 'Target', stateKey: 'sensors.lineLaser.enabled', type: 'toggle' },
                            { name: 'TOF', icon: 'radio',stateKey: 'sensors.tof.enabled', type: 'toggle' }
                        ]
                    }
                }
            },
            containers: {
                title: '容器状态',
                icon: 'package',
                subGroups: {
                    waterTank: {
                        label: '水箱',
                        icon: 'droplet',
                        tests: [
                            { name: '安装', icon: 'check-square', stateKey: 'containers.waterTank.attached', type: 'toggle' },
                            { name: '水量', icon: 'droplets', stateKey: 'containers.waterTank.level', type: 'slider', min: 0, max: 1000, step: 1 }
                        ]
                    },
                    dustbin: {
                        label: '尘盒',
                        icon: 'trash', // 新增组图标
                        tests: [
                            { name: '安装', icon: 'check-square', stateKey: 'containers.dustbin.attached', type: 'toggle' },
                            { name: '已满', icon: 'alert-triangle', stateKey: 'containers.dustbin.full', type: 'toggle' }
                        ]
                    },
                    cleaningFluid: {  // 新增清洁液容器组
                        label: '清洁液',
                        icon: 'beaker',
                        tests: [
                            { name: '安装', icon: 'check-square', stateKey: 'containers.cleaningFluid.attached', type: 'toggle' },
                            { name: '液位', icon: 'droplets', stateKey: 'containers.cleaningFluid.level', type: 'slider', min: 0, max: 1000, step: 1 },
                            {
                                name: '类型',
                                icon: 'filter',
                                stateKey: 'containers.cleaningFluid.type',
                                type: 'select',
                                options: [
                                    { value: 'none', label: '无' },
                                    { value: 'standard', label: '标准' },
                                    { value: 'strong', label: '强力' }
                                ]
                            }
                        ]
                    }
                }
            },
            keyLeds: {
                title: '按键&LED',
                icon: 'keyboard',  // 改用更合适的图标
                subGroups: {
                    homeButton: {
                        label: 'Home键',
                        icon: 'home',
                        tests: [
                            { name: 'LED', icon: 'lamp', stateKey: 'keyLeds.homeButton.ledOn', type: 'toggle' },
                            { name: 'H按键', icon: 'arrow-big-down-dash', stateKey: 'keyLeds.homeButton.pressed', type: 'toggle' }
                        ]
                    },
                    powerButton: {
                        label: 'Power键',
                        icon: 'power',  // 使用电源图标，因为Dock键通常用于充电对接
                        tests: [
                            { name: 'LED', icon: 'lamp', stateKey: 'keyLeds.powerButton.ledOn', type: 'toggle' },
                            { name: 'P按键', icon: 'arrow-down-0-1', stateKey: 'keyLeds.powerButton.pressed', type: 'toggle' }
                        ]
                    }
                }
            }
        };

        this.init();
    }

    init() {
        this.renderUI();
        this.bindEvents();
        this.subscribeToStateChanges();
    }

    renderUI() {
        this.container.innerHTML = `
            <div class="component-test-panel ${this.isTestMode ? 'test-mode' : ''}">
                <div class="test-panel-content">
                    <!-- 测试模式开关 -->
                    <div class="panel-header">
                        <div class="test-mode-switch" id="test-mode-switch">
                            <span>测试模式</span>
                            <div class="switch-container">
                                <div class="switch-button ${this.isTestMode ? 'active' : ''}"
                                     data-action="toggle-test-mode">
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 测试组容器 -->
                    <div class="test-groups-container">
                        ${this.renderGroups()}
                    </div>
                    <div id="test-panel-logo"></div>
                </div>
            </div>
        `;

        // 初始化Logo组件
        new LogoComponent(document.getElementById('test-panel-logo'));

        // 初始化Lucide图标
        lucide.createIcons();
    }

    renderGroups() {
        return Object.entries(this.testGroups)
            .map(([key, group]) => `
                <section class="test-section" data-group="${key}">
                    <h3 class="section-title">
                        <i data-lucide="${group.icon}"></i>
                        <span>${group.title}</span>
                    </h3>
                    <div class="test-subgroups-container">
                        ${Object.entries(group.subGroups)
                            .map(([subKey, subGroup]) => this.renderSubGroup(subKey, subGroup))
                            .join('')}
                    </div>
                </section>
            `)
            .join('');
    }

    renderGroup(key, group) {
        if (!group) return '';

        return `
            <section class="test-section" data-group="${key}">
                <h3 class="section-title">
                    <i data-lucide="truck"></i>
                    <span>${group.title}</span>
                </h3>
                ${group.subGroups ?
                    `<div class="test-subgroups-container">
                        ${Object.entries(group.subGroups)
                            .map(([subKey, subGroup]) => this.renderSubGroup(subKey, subGroup))
                            .join('')}
                    </div>` :
                    this.renderTests(group.tests || [])}
            </section>
        `;
    }

    renderSubGroup(key, subGroup) {
        return `
            <div class="test-subgroup">
                <div class="subgroup-content">
                    <h4 class="subgroup-label">
                        <i data-lucide="${subGroup.icon}"></i>
                        <span>${subGroup.label}</span>
                    </h4>
                    <div class="test-list">
                        ${(subGroup.tests || []).map(test => this.renderTestControl(test)).join('')}
                    </div>
                </div>
            </div>
        `;
    }
    renderTests(tests) {
        if (!tests || !Array.isArray(tests) || tests.length === 0) {
            return '<div class="test-list empty"></div>';
        }

        return `
            <div class="test-list">
                ${tests.map(test => this.renderTestControl(test)).filter(Boolean).join('')}
            </div>
        `;
    }

    renderTestControl(test) {
        const currentValue = this.stateManager?.getStateValue(test.stateKey) || 0;

        switch (test.type) {
            case 'toggle':
                return `
                    <div class="test-control">
                        <button class="test-button ${currentValue ? 'active' : ''}"
                                data-state-key="${test.stateKey}">
                            <i data-lucide="${test.icon}"></i>
                            <span>${test.name}</span>
                        </button>
                    </div>
                `;
            case 'slider':
                return `
                <div class="test-control">
                    <span class="test-label">
                        <i data-lucide="${test.icon}"></i>
                        <span>${test.name}</span>
                    </span>
                    <div class="value-control">
                        <input type="text"
                               class="value-input"
                               value="${currentValue}"
                               data-state-key="${test.stateKey}"
                               data-min="${test.min}"
                               data-max="${test.max}"
                               data-step="${test.step}">
                        <span class="unit-label">mm/s</span>
                    </div>
                </div>
            `;
        }
    }

    bindEvents() {
        // 使用事件委托处理所有交互
        this.container.addEventListener('click', (event) => {
            // 处理测试模式开关
            if (event.target.closest('[data-action="toggle-test-mode"]')) {
                this.toggleTestMode();
                return;
            }

            // 非测试模式下不处理其他点击
            if (!this.isTestMode) return;

            // 处理按钮点击
            const button = event.target.closest('.test-button');
            if (button) {
                const stateKey = button.dataset.stateKey;
                if (stateKey) {
                    this.handleButtonClick(button, stateKey);
                }
            }
        });

        // 处理输入框，只接受数字和小数点
        this.container.addEventListener('input', (event) => {
            if (!this.isTestMode) return;

            if (event.target.classList.contains('value-input')) {
                const value = event.target.value;
                // 只允许数字和小数点
                if (!/^\d*\.?\d*$/.test(value)) {
                    event.target.value = value.replace(/[^\d.]/g, '');
                }
            }
        });

        // 添加新的事件监听器来处理输入完成
        this.container.addEventListener('blur', (event) => {
            if (!this.isTestMode) return;

            if (event.target.classList.contains('value-input')) {
                // 防止与 keydown 事件重复触发
                if (!event.target.dataset.handled) {
                    this.handleInputComplete(event.target);
                }
                delete event.target.dataset.handled;
            }
        }, true);

        // 修改 keydown 事件处理
        this.container.addEventListener('keydown', (event) => {
            if (!this.isTestMode) return;

            if (event.target.classList.contains('value-input') && event.key === 'Enter') {
                event.target.dataset.handled = 'true';
                this.handleInputComplete(event.target);
                event.target.blur();
            }
        });
    }

    // 处理输入完成的方法
    handleInputComplete(inputElement) {
        const stateKey = inputElement.dataset.stateKey;
        const rawValue = inputElement.value;
        const min = parseFloat(inputElement.dataset.min);
        const max = parseFloat(inputElement.dataset.max);

        // 解析数值
        let value = parseFloat(rawValue);

        // 检查是否为有效数字
        if (isNaN(value)) {
            value = min;
        }

        // 限制范围
        value = Math.max(min, Math.min(max, value));

        // 更新输入框显示
        inputElement.value = value;

        // 更新状态并发送数据
        this.handleValueInput(stateKey, value);
    }

    handleValueInput(stateKey, value) {
        this.stateManager.updateComponentState(stateKey, value);
        this.updateUI(this.stateManager.getState());

        // Construct and send protobuf message based on state key
        this.sendMockChassisData(stateKey, value);
    }

    // 添加测试模式切换方法
    toggleTestMode() {
        this.isTestMode = !this.isTestMode;

        const panel = this.container.querySelector('.component-test-panel');
        const switchButton = this.container.querySelector('.switch-button');

        if (panel) {
            panel.classList.toggle('test-mode', this.isTestMode);
        }
        if (switchButton) {
            switchButton.classList.toggle('active', this.isTestMode);
        }

        console.log('Toggling test mode to:', this.isTestMode); // 添加日志
    }

    handleButtonClick(button, stateKey) {
        const currentValue = this.stateManager.getStateValue(stateKey);
        const newValue = !currentValue;
        this.stateManager.updateComponentState(stateKey, newValue);
        this.updateUI(this.stateManager.getState());

        // Construct and send protobuf message based on state key
        this.sendMockChassisData(stateKey, newValue);
    }

    sendMockChassisData(stateKey, value) {
        const ws = window.webSocketHandler;
        if (!ws.isConnected) return;

        // 构造模拟数据
        const mockData = this.createMockChassisData(stateKey, value);

        console.log("component simulate: ", stateKey, ", value: ", value);

        ws.sendMessage("ChassisMiscGroup", "chass_misc", {
            info: mockData
        });
    }

    createMockChassisData(stateKey, value) {
        const mockInfo = {};

        const stateMapping = {
            // Wheels
            'motion.wheels.left.rotating': () => {
                mockInfo.wheels = {wheelLeft: {val: {value}}};
            },
            'motion.wheels.right.rotating': () => {
                mockInfo.wheels = {wheelRight: {val: {value}}};
            },
            'motion.wheels.left.offGround': () => {
                mockInfo.wheels = {wheelLeft: {en: {value}}};
            },
            'motion.wheels.right.offGround': () => {
                mockInfo.wheels = {wheelRight: {en: {value}}};
            },
            'motion.wheels.left.speed': () => {
                mockInfo.wheels = {wheelLeft: {val: {value}}};
            },
            'motion.wheels.right.speed': () => {
                mockInfo.wheels = {wheelRight: {val: {value}}};
            },

            // Brushes
            'cleaning.brush.main.enabled': () => {
                mockInfo.brushs = {rollBrushMain: {en: {value}}};
            },
            'cleaning.brush.side.enabled': () => {
                mockInfo.brushs = {sideBrushLeft: {en: {value}}};
            },
            'cleaning.brush.main.speed': () => {
                mockInfo.brushs = {rollBrushMain: {val: {value}}};
            },
            'cleaning.brush.side.speed': () => {
                mockInfo.brushs = {sideBrushLeft: {val: {value}}};
            },

            // Vacuum
            'cleaning.vacuum.enabled': () => {
                mockInfo.suckFan = {suckFan_1: {en: {value}}};
            },
            'cleaning.vacuum.fanSpeed': (val) => {
                mockInfo.suckFan = {suckFan_1: {val: {value: Math.floor(val)}}};
            },

            // Mop
            'cleaning.mop.lift': () => {
                mockInfo.mop = {lift: {en: {value}}};
            },
            'cleaning.mop.vibrate': () => {
                mockInfo.mop = {work: {en: {value}}};
            },
            'cleaning.mop.waterFlow': (val) => {
                mockInfo.mop = {water: {val: {value: val}}};
            },

            // Camera, TODO
            'sensors.camera.main.enabled': () => {
                mockInfo.periphSoc = {camera: {en: {value}}};
            },

            // Lidar
            'sensors.lidar.switches.front': () => {
                mockInfo.bumps = {bumpLidarF: {en: {value}}};
            },
            'sensors.lidar.switches.back': () => {
                mockInfo.bumps = {bumpLidarB: {en: {value}}};
            },
            'sensors.lidar.switches.left': () => {
                mockInfo.bumps = {bumpLidarL: {en: {value}}};
            },
            'sensors.lidar.switches.right': () => {
                mockInfo.bumps = {bumpLidarR: {en: {value}}};
            },
            'sensors.lidar.rotating': () => {
                mockInfo.periphSoc = {lidar: {en: {value}}};
            },
            'sensors.lidar.speed': () => {
                mockInfo.periphSoc = {lidar: {val: {value}}};
            },

            // Front bump
            'sensors.frontBumper.left': () => {
                mockInfo.bumps = {bumpLeft: {en: {value}}};
            },
            'sensors.frontBumper.right': () => {
                mockInfo.bumps = {bumpRight: {en: {value}}};
            },

            // Drops
            'sensors.cliff.left': () => {
                mockInfo.drops = {dropLeft: {en: {value}}};
            },
            'sensors.cliff.frontLeft': () => {
                mockInfo.drops = {dropLeftMid: {en: {value}}};
            },
            'sensors.cliff.frontRight': () => {
                mockInfo.drops = {dropRightMid: {en: {value}}};
            },
            'sensors.cliff.right': () => {
                mockInfo.drops = {dropRight: {en: {value}}};
            },

            // Infra-Red
            'sensors.ir.left': () => {
                mockInfo.dockSig = {left: {en: {value}}};
            },
            'sensors.ir.leftMid': () => {
                mockInfo.dockSig = {leftMid: {en: {value}}};
            },
            'sensors.ir.leftRear': () => {
                mockInfo.dockSig = {leftRear: {en: {value}}};
            },
            'sensors.ir.rightRear': () => {
                mockInfo.dockSig = {rightRear: {en: {value}}};
            },
            'sensors.ir.rightMid': () => {
                mockInfo.dockSig = {rightMid: {en: {value}}};
            },
            'sensors.ir.right': () => {
                mockInfo.dockSig = {right: {en: {value}}};
            },

            // Containers
            'containers.waterTank.attached': () => {
                mockInfo.tankBox = {cleanTank: {en: {value}}};
            },
            'containers.waterTank.level': () => {
                mockInfo.tankBox = {cleanTank: {val: {value}}};
            },
            'containers.dustbin.attached': () => {
                mockInfo.tankBox = {dustBox: {en: {value}}};
            },
            'containers.dustbin.full': () => {
                mockInfo.tankBox = {dustBox: {val: {value}}};
            },
            'containers.cleaningFluid.attached': () => {
                mockInfo.tankBox = {detergentTank: {en: {value}}};
            },
            'containers.cleaningFluid.level': () => {
                mockInfo.tankBox = {detergentTank: {val: {value}}};
            },

            // LEDs
            'keyLeds.homeButton.ledOn': () => {
                mockInfo.leds = {homeLed: {en: {value}}};
            },
            'keyLeds.powerButton.ledOn': () => {
                mockInfo.leds = {powerLed: {en: {value}}};
            },
            // Keys
            'keyLeds.homeButton.pressed': () => {
                mockInfo.keys = {dock: {en: {value}}};
            },
            'keyLeds.powerButton.pressed': () => {
                mockInfo.keys = {power: {en: {value}}};
            },

            // TOF
            'sensors.tof.enabled': () => {
                mockInfo.dtofs = {dtof_1: {en: {value}}};
            },
            // Line laser
            'sensors.lineLaser.enabled': () => {
                mockInfo.llasers = {llaser_1: {en: {value}}};
            }
        };

        if (stateMapping[stateKey]) {
            stateMapping[stateKey](value);
        }

        return mockInfo;
    }

    subscribeToStateChanges() {
        this.stateManager.addListener(state => {
            this.updateUI(state);
        });
    }

    updateUI(state) {
        // 遍历所有控件，更新状态
        this.container.querySelectorAll('[data-state-key]').forEach(control => {
            const stateKey = control.dataset.stateKey;
            if (!stateKey) return;

            const value = this.stateManager.getStateValue(stateKey);

            if (control.classList.contains('test-button')) {
                // 更新按钮状态
                control.classList.toggle('active', !!value);
            } else if (control.type === 'range') {
                // 更新滑块值
                control.value = value || 0;
                const display = control.nextElementSibling;
                if (display) {
                    display.textContent = (value || 0).toFixed(2);
                }
            } else if (control.tagName.toLowerCase() === 'select') {
                // 更新选择值
                control.value = value || control.options[0].value;
            }
        });
    }

    destroy() {
        if (this.stateManager) {
            this.stateManager.removeListener(this.updateUI.bind(this));
        }
        if (this.container) {
            this.container.innerHTML = '';
        }
    }
}

// 导出到全局作用域
if (typeof window !== 'undefined') {
    window.ComponentStateTestPanel = ComponentStateTestPanel;
}

// CommonJS 模块导出
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        ComponentStateTestPanel
    };
}
